﻿using System;
using System.Threading;
using System.Windows.Threading;
using System.Collections.Generic;
using System.Linq;
using GameLight.Graphics;
using GameLight.Input;
using GameLight.Scene;
using GameLight.Sound;

namespace UnitTests
{
	public class TestDispatcher
	{
		public static readonly int numberOfThreads = 4;

		public event EventHandler Completed;

		private ThreadCommunicator communicator;
		private List<TestThread> testThreads = new List<TestThread>();
		private bool completeFired = false;

		public TestDispatcher(ThreadCommunicator communicator)
		{
			this.communicator = communicator;
		}

		public void Refresh()
		{
			if (!this.uiThreadWorker.IsDone)
			{
				this.uiThreadWorker.Go();
			}
			List<TestThread> deadThreads = new List<TestThread>();
			for (int i = 0; i < this.testThreads.Count; ++i)
			{
				if (this.testThreads[i].IsDone)
				{
					this.testThreads.RemoveAt(i);
					i--;
				}
			}

			if (this.testThreads.Count == 0 && !this.completeFired && this.Completed != null)
			{
				this.completeFired = true;
				this.Completed(this, EventArgs.Empty);
			}
		}


		private TestThread uiThreadWorker;

		public void Start()
		{
			for (int i = 1; i < numberOfThreads; ++i)
			{
				TestThread testThreadWorker = new TestThread(this.communicator, false);
				this.testThreads.Add(testThreadWorker);
				Thread thread = new Thread(new ParameterizedThreadStart((unused) => testThreadWorker.Go()));
				thread.Start();
			}

			this.uiThreadWorker = new TestThread(this.communicator, true);
			this.testThreads.Add(uiThreadWorker);
		}
	}
}
